package com.th.dao;

import com.th.entity.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public  class UserDaoImp implements UserDao {
    JdbcTemplate jdbcTemplate;

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;

    }
    @Override
    public void insertUser(User user)
    {
        String sql = "insert into user values(?,?,?,?,?,?,?,?,?,?)";
        jdbcTemplate.update(sql,user.getOpenid(),user.getName(),user.getAge(),user.getSex(),user.getPhone(),user.getAddress(),user.getCollege(),user.getMajor(),user.getGrade(),user.getStuNum());

    }
    @Override
    public void deleteUser(String openid)
    {
        String sql = "delete from user where openid=?";
        jdbcTemplate.update(sql,openid);
    }
    @Override
    public void updateUser(User user)
    {
        String sql = "update user set grade=?, sex=?, age=?, name = ?, phone = ?, address = ?, college = ?, major = ?, stuNum = ? where openid = ?";
        jdbcTemplate.update(sql,user.getGrade(), user.getSex(), user.getAge(), user.getName(),user.getPhone(),user.getAddress(),user.getCollege(),user.getMajor(),user.getStuNum(),user.getOpenid());
    }
    @Override
    public User selectUser(String openid)
    {
        String sql = "select * from user where openid=?";
        User user = null;
        try
        {
            user = jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class),openid);
        }
        catch (Exception e)
        {
            return user;
        }
        return user;
    }
    @Override
    public List<User> selectUsers()
    {
        String sql = "select * from user";
        return jdbcTemplate.query(sql,new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                User user = new User();
                user.setName(rs.getString("name"));
                user.setSex(rs.getString("sex"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                user.setCollege(rs.getString("college"));
                user.setMajor(rs.getString("major"));
                user.setStuNum(rs.getString("stuNum"));
                user.setAge(rs.getInt("age"));
                user.setOpenid(rs.getString("openid"));
                user.setGrade(rs.getInt("grade"));
                // 如果还有其他列，继续设置...
                return user;
            }
        });
    }

}
